package com.wingsoft.common.utils.oss;


import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.wingsoft.common.config.AliyunOssConfig;
import com.wingsoft.common.utils.file.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Component
public class AliyunOssUploadUtils {
    private static AliyunOssConfig aliyunOssConfig;
    /**
     * 使用构造方法注入配置信息
     */
    @Autowired
    public AliyunOssUploadUtils(AliyunOssConfig aliyunOssConfig) {
        AliyunOssUploadUtils.aliyunOssConfig = aliyunOssConfig;
    }
    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    public static String uploadFile(MultipartFile file) throws Exception {
        // 生成 OSSClient
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
        // 原始文件名称
        // String originalFilename = file.getOriginalFilename();
        // 编码文件名
        String filePathName = FileUploadUtils.extractFilename(file);
        // 文件路径名称
        filePathName = aliyunOssConfig.getFilehost() + "/" + filePathName;
        try {
            ossClient.putObject(aliyunOssConfig.getBucketName(), filePathName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return aliyunOssConfig.getUrl() + "/" + filePathName;

    }

    /*public static Map<String,String> getSignedUrl(String objectName) {

        DefaultCredentialProvider credentialsProvider = CredentialsProviderFactory.newDefaultCredentialProvider(aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());

        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(aliyunOssConfig.getEndpoint())
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(aliyunOssConfig.getRegion())
                .build();

        URL signedUrl = null;
        String fileUrl = null;
        try {
            // 指定生成的预签名URL过期时间，单位为毫秒。本示例以设置过期时间为1小时为例。
            Date expiration = new Date(new Date().getTime() + 3600 * 1000L);

            // 编码文件名
            String filePathName = FileUploadUtils.extractFilename(objectName);
            filePathName = aliyunOssConfig.getFilehost() + "/" + filePathName;
            // 文件路径名称
            fileUrl = aliyunOssConfig.getUrl() + "/" + filePathName;


            // 生成预签名URL。
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(aliyunOssConfig.getBucketName(), filePathName, HttpMethod.PUT);
            // 设置过期时间。
            request.setExpiration(expiration);
            // 通过HTTP PUT请求生成预签名URL。
            signedUrl = ossClient.generatePresignedUrl(request);
            // 打印预签名URL。
            System.out.println("signed url for putObject: " + signedUrl);

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("signedUrl", signedUrl.toString());
        map.put("url", fileUrl);
        map.put("fileName", objectName);
        return map;
    }*/



    public static Map<String,String> getSignedUrl(String objectName,String contentType) throws com.aliyuncs.exceptions.ClientException {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());

        URL signedUrl = null;
        String fileUrl = null;
        try {
            // 指定生成的预签名URL过期时间，单位为毫秒。本示例以设置过期时间为1小时为例。
            Date expiration = new Date(new Date().getTime() + 3600 * 1000L);

            // 编码文件名
            String filePathName = FileUploadUtils.extractFilename(objectName);
            filePathName = aliyunOssConfig.getFilehost() + "/" + filePathName;
            // 文件路径名称
            fileUrl = aliyunOssConfig.getUrl() + "/" + filePathName;

            // 生成预签名URL。
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(aliyunOssConfig.getBucketName(), filePathName, HttpMethod.PUT);
            // 设置过期时间。
            request.setExpiration(expiration);
            Map<String, String> headers = new HashMap<>();
            headers.put(OSSHeaders.CONTENT_TYPE, contentType);
            request.setHeaders(headers);
            // 通过HTTP PUT请求生成预签名URL。
            signedUrl = ossClient.generatePresignedUrl(request);
            // 打印预签名URL。
            System.out.println("signed url for putObject: " + signedUrl);


        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("signedUrl", signedUrl.toString());
        map.put("url", fileUrl);
        map.put("fileName", objectName);
        return map;
    }


    public static String uploadBuffer(byte[] result,String fileName) {
        // 生成 OSSClient
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
        // 编码文件名
        String filePathName = FileUploadUtils.extractFilename(fileName);
        filePathName = aliyunOssConfig.getFilehost() + "/" + filePathName;
        // 文件路径名称
        String fileUrl = aliyunOssConfig.getUrl() + "/" + filePathName;
        try {
            InputStream inputStream = new ByteArrayInputStream(result);
            ossClient.putObject(aliyunOssConfig.getBucketName(), filePathName, inputStream);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return fileUrl;
    }

    public static String uploadBuffer(byte[] result) throws Exception {
        // 生成 OSSClient
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
        String filePathName = System.currentTimeMillis()+".png";
        try {
            InputStream inputStream = new ByteArrayInputStream(result);
            ossClient.putObject(aliyunOssConfig.getBucketName(), filePathName, inputStream);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return aliyunOssConfig.getUrl() + "/" + filePathName;
    }
}
